<template>
  <div v-if="isLoadInfo">
    <van-image
        width="100vw"
        height="calc(100vw * (380 / 750))"
        :src="dataInfo.thumb"
        fit="cover"
    >
      <template v-slot:error>
        <div class="w-full h-full flex items-center justify-center bg-white">
          <van-icon name="photo-o" class="text-gray-200" color="#999999"></van-icon>
        </div>
      </template>
    </van-image>
    <div style="background-color: #f9f9f9">
      <div class="pt-2 bg-white p-3 pb-4">
        <span class="text-2xl font-bold">{{ dataInfo.name }}</span>
        <div class="flex flex-col pt-3">
          <span class="pb-1 flex items-center">
            <van-icon name="clock-o" size="18" color="#666666" class="pr-2"/>
            <span class="text-sm leading-6" style="color: #666666">{{ formattedDate }}</span>
          </span>
          <span class="flex items-center">
            <van-icon name="location-o" size="18" color="#666666" class="pr-2"/>
            <span class="text-sm leading-6" style="color: #666666">{{ dataInfo.address }}</span>
          </span>
        </div>
        <div class="flex flex-col pt-10">
          <span class="font-bold pb-2">{{ dataInfo.introduce.name }}</span>
          <span class="pt-1 text-sm leading-7" style="color: #666666;text-indent: 1em;">{{ dataInfo.introduce.introduce }}</span>
        </div>
      </div>

      <div class="bg-white mt-2 p-3">
        <span class="font-bold pb-2">{{ dataInfo.exhibition.name }}</span>
        <div class="flex flex-col pt-4 pb-2">
          <van-row gutter="20" class="mb-2 pb-2" v-for="item in dataInfo.exhibition.exhibitions" :key="item.name">
            <van-col span="6" class="flex items-center justify-center">
              <van-image
                  width="24vw"
                  height="calc(24vw * (380 / 750))"
                  :src="item.thumb"
                  fit="cover"
                  radius="5"/>
            </van-col>
            <van-col span="18">
              <div class="flex flex-col">
                <span class="font-bold" style="color: #333333">{{ item.name }}</span>
                <div class="flex pt-3">
                  <span class="flex items-center justify-center pr-2">
                    <van-icon name="down" size="18" color="#999999" class="pr-1"/>
                    <span class="text-sm leading-6" style="color: #999999">{{ item.download }}</span>
                  </span>
                  <span class="flex items-center justify-center">
                    <van-icon name="eye-o" size="20" color="#999999" class="pr-1"/>
                    <span class="text-sm leading-6" style="color: #999999">{{ item.view }}</span>
                  </span>
                </div>
              </div>
            </van-col>
          </van-row>
        </div>
      </div>

      <div class="bg-white mt-2 p-3">
        <span class="font-bold pb-2">{{ dataInfo.speaker.name }}</span>
        <div class="flex flex-col pt-4">
          <van-row class="flex items-center justify-start pb-2" v-for="item in dataInfo.speaker.speakers" :key="item.name">
            <van-col span="6">
              <van-image width="70"
                         :src="item.thumb"
                         fit="cover"
                         round
                         class="border border-gray-100 p-0.5"
              />
            </van-col>
            <van-col span="18" class="flex items-center justify-start">
              <div class="flex flex-col">
                <span class="font-bold" style="color: #333333">{{ item.name }}</span>
                <div class="text-sm pt-1">
                  <span style="color: #999999">{{ item.desc }}</span>
                </div>
              </div>
            </van-col>
          </van-row>
        </div>
      </div>

      <div class="bg-white mt-2 p-3">
        <span class="font-bold">{{ dataInfo.schedule.name }}</span>
        <div class="pt-4">
          <van-steps direction="vertical" :active="0">
            <van-step v-for="(item, key) in dataInfo.schedule.schedules" :key="key">
              <template #active-icon>
                <div class="rounded-full bg-gray-200 ">
                  <van-icon name="stop" size="12" color="#ffffff"/>
                </div>
              </template>
              <template #inactive-icon>
                <div class="rounded-full bg-gray-200">
                  <van-icon name="stop" size="12" color="#ffffff"/>
                </div>
              </template>
              <div class="pl-2 flex flex-col" style="color: #666666">
                <span>{{ item.time }}</span>
                <span class="font-bold pt-2">{{ item.name }}</span>
                <div v-if="item.speaker && getSpeaker(item.speaker)" class="h-20 mt-2 rounded-md" style="background-color: #f9f9f9">
                  <van-row class="flex items-center justify-start p-2">
                    <van-col span="6">
                      <van-image width="70"
                                 :src="getSpeakerDescription(item.speaker,'thumb')"
                                 fit="cover"
                                 round
                                 class="border-4 border-white"
                      />
                    </van-col>
                    <van-col span="18" class="flex items-center justify-start">
                      <div class="flex flex-col">
                        <span class="font-bold" style="color: #333333">{{ getSpeakerDescription(item.speaker,'name') }}</span>
                        <div class="text-sm pt-1">
                          <span style="color: #999999">{{ getSpeakerDescription(item.speaker,'desc') }}</span>
                        </div>
                      </div>
                    </van-col>
                  </van-row>
                </div>
              </div>
            </van-step>
          </van-steps>
        </div>
      </div>

      <div class="bg-white mt-2 p-3">
        <span class="font-bold pb-2">{{ dataInfo.organization.name }}</span>
        <div class="flex flex-col pt-4">
          <van-row class="flex items-center justify-start" v-for="item in dataInfo.organization.organizations" :key="item.name">
            <van-col span="6">
              <div class="flex justify-center items-center p-2">
                <van-image width="70"
                           height="70"
                           :src="item.thumb"
                           fit="cover"
                           class="border border-gray-100"
                           radius="10"
                />
              </div>
            </van-col>
            <van-col span="18" class="flex items-center justify-start pl-2">
              <div class="flex flex-col">
                <span class="font-bold text-lg" style="color: #333333">{{ item.type }}</span>
                <div class="text-sm pt-1">
                  <span style="color: #999999">{{ item.name }}</span>
                </div>
              </div>
            </van-col>
          </van-row>
        </div>
      </div>

      <div class="bg-white mt-2 p-3 flex flex-col">
        <span class="font-bold pb-2">{{ dataInfo.notice.name }}</span>
        <span class="pt-1 text-sm leading-7" style="color: #666666;">{{ dataInfo.notice.notice }}</span>
      </div>

      <div class="bg-white mt-2 p-3 flex flex-col">
        <span class="font-bold pb-2">{{ dataInfo.contact.name }}</span>
        <div class="pt-1 text-sm leading-7">
          <van-row v-for="item in dataInfo.contact.contacts" :key="item.code">
            <van-col span="6">
              <span style="color: #666666;">{{ item.name }}：</span>
            </van-col>
            <van-col span="16">
              <span class="text-blue-500" @click="dealContact(item)">{{ item.value }}</span>
            </van-col>
          </van-row>
        </div>
      </div>
      <div class="bg-white mt-2 h-14"></div>

      <van-action-bar class="z-10">
        <span v-show="showCountdown" class="pr-10 pl-4" style="color: #666666;">
          还有<span class="text-red-500">{{ countdown.days }}</span>天
          <span class="text-red-500">{{ countdown.hours }}</span>小时
          <span class="text-red-500">{{ countdown.minutes }}</span>分钟开始
        </span>
        <van-action-bar-button type="danger" :color="dataInfo.registration.color" :text="buttonText" @click="register" />
      </van-action-bar>

      <component
          v-if="ctaUuid && ctaShow"
          v-model:ctaShow="ctaShow"
          :omniUserUuid="omniUserUuid"
          :ctaType="ctaType"
          :ctaUuid="ctaUuid"
          sceneType="campaign"
          :sceneUuid="campaignUuid"
          @updateCtaShow="ctaShow = false"
          @updateCtaStatus="handleCtaStatusUpdate"
          :is="ctaFormComponent"/>

    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, onUnmounted,onBeforeUnmount, computed,defineAsyncComponent } from 'vue';
import {useRoute} from 'vue-router';
import { copyText } from '@/utils/copy';
import moment from 'moment';
import {checkRegister, CampaignType, campaignInfo,logRecord} from '@/api/campaign';
import {CtaType} from "@/api/cta.ts";
import {initWechat} from "@/utils/wechat.ts";
// 获取本地存储的用户 UUID
const omniUserUuid = localStorage.getItem('omni_user_uuid') as string;
const ctaShow = ref<boolean>(false);
const isRegister = ref(false);
const isLoadInfo = ref<boolean>(false)
const ctaUuid = ref("");
const ctaType = ref<CtaType>('');

// 获取路由参数
const route = useRoute();
const campaignUuid = route.params.campaignUuid as string;
const aggListUuid = route.params.aggListUuid as string;
const pushId = route.query.pushId as string;
const ctaFormComponent = defineAsyncComponent(() => import("@/views/components/cta/CtaForm.vue"))

const tomorrowWithTime = (inputTime:string) => {
  // 获取当前时间
  const now = moment();
  // 获取明天的日期
  const tomorrow = now.clone().add(1, 'days');
  // 设置明天的具体时间
  const [hours, minutes, seconds] = inputTime.split(':').map(Number);
  tomorrow.set({
    hour: hours,
    minute: minutes,
    second: seconds,
    millisecond: 0
  });
  // 格式化日期和时间
  return tomorrow.format('YYYY-MM-DD HH:mm:ss');
}

// 数据信息
const dataInfo = ref<CampaignType>({
  uuid: "xx",
  name: "数字化落地，破局增长 营销自动化技术，为B2B企业增长加速",
  thumb: "",
  thumb_material_uuid: "",
  start_at: tomorrowWithTime("08:00:00"),
  end_at: tomorrowWithTime("12:00:00"),
  address: "上海市国家会展中心",
  introduce: {
    name: '会议介绍',
    introduce: '由xxx举办的第二届数字化营销增长年会将于2024年12月在上海举办，大会以“数字化落地，破局增长 营销自动化技术，为B2B企业增长加速”为主题，本场会议全面聚焦大环境下企业数字化营销的变革，精准匹配数字化增产执行方案，助力企业创造与用户在线互动的场景。'
  },
  exhibition: {
    name: '展品',
    exhibitions: [
      {
        name: "2024高客单价行业微信数据报告",
        thumb_material_uuid: "",
        file_material_uuid: "",
        thumb: "https://app.jingsocial.com//upload/images/169760089572903.jpeg",
        view: 99,
        download: 59
      },
      {
        name: "AI如何加速B2B企业营销升级？",
        thumb_material_uuid: "",
        file_material_uuid: "",
        thumb: "https://app.jingsocial.com/upload/images/171645745447862.png",
        view: 99,
        download: 59
      }
    ]
  },
  speaker: {
    name: '主讲嘉宾',
    speakers: [
      { name: "张三", desc: "聚光广传 CEO", thumb_material_uuid: "", thumb: "https://app.jingsocial.com/upload/images/169744058771031.jpg" },
      { name: "李四", desc: "保利威 副总裁", thumb_material_uuid: "", thumb: "https://app.jingsocial.com/upload/images/169719454138646.jpg" },
    ]
  },
  schedule: {
    name: '议程',
    schedules: [
      {
        name: "注册签到",
        time: "08:00 - 09:00",
        startTime: "08:00",
        endTime: "09:00",
        speaker: ""
      },
      {
        name: "欢迎致辞",
        time: "09:00 - 09:10",
        startTime: "09:00",
        endTime: "09:10",
        speaker: "",
      },
      {
        name: "企业如何通过营销自动化，建立市场拓新增长体系",
        time: "09:10 - 10:30",
        startTime: "09:10",
        endTime: "10:30",
        speaker: "张三"
      },
      {
        name: "企业如何通过营销自动化，建立市场拓新增长体系",
        time: "11:00 - 12:00",
        startTime: "11:00",
        endTime: "12:00",
        speaker: "李四"
      },
      {
        name: "结束",
        time: "12:00",
        startTime: "12:00",
        endTime: "12:00",
        speaker: ""
      },
    ]
  },
  organization: {
    name: '组织机构',
    organizations: [
      { name: "主办机构名称", type: "主办方", thumb: "http://www.shimao.com/upload/33/common/logo.jpg", thumb_material_uuid: "" },
      { name: "协办机构名称", type: "协办方", thumb: "https://app.jingsocial.com/upload/images/169719542753165.jpg", thumb_material_uuid: "" },
    ]
  },
  notice: {
    name: '活动须知',
    notice: '请您在会议开始前15分钟入场，会议结束后会为您发送活动相关资料。'
  },
  contact: {
    name: '联系我们',
    contacts: [
      { code: "website", name: "网站", value: "www.shuangying.tech" },
      { code: "mobile", name: "电话", value: "400-000-0000" },
      { code: "wechat", name: "公众号", value: "xxx" },
      { code: "email", name: "邮箱", value: "xxxx@xxx.com" }
    ],
  },
  registration: {
    name: "立即报名",
    color: "#000000",
    cta_info: ["form", "qVaUKkeh4CGUf28CcZYKBY"],
    review:true
  },
});

// 获取当前时间
const start = computed(() => moment(dataInfo.value.start_at));
const end = computed(() => moment(dataInfo.value.end_at));

const buttonText = computed(() => {
  if (moment().isBefore(start.value)) {
    return isRegister.value ? "报名成功" : "立即报名";
  } else if (moment().isBefore(end.value)) {
    return isRegister.value ? "活动进行中，去签到" : "活动进行中";
  } else {
    return "活动结束";
  }
});

// 显示倒计时
const showCountdown = computed(() => moment().isBefore(start.value));

const countdown = ref<{ days: number; hours: number; minutes: number }>({
  days: 0,
  hours: 0,
  minutes: 0
});


const updateCountdown = () => {
  const targetTime = moment(dataInfo.value.start_at);
  const duration = moment.duration(targetTime.diff(moment()));

  countdown.value.days = Math.floor(duration.asDays());
  countdown.value.hours = Math.floor(duration.asHours() % 24);
  countdown.value.minutes = Math.floor(duration.asMinutes() % 60);
};

let intervalId: ReturnType<typeof setInterval>;

const imgUrl = ref("https://www.shuangying.tech/upload/33/1/mcb4Jm6NtTwrcvDEz4CSb.jpg")
let enterTime: number;

onMounted(() => {
  enterTime = Date.now(); // 记录进入页面的时间戳
  getCampaignInfo()
  getRegisterStatus();
  // logRecordAction("campaign_view");
});

onBeforeUnmount(() => {
  const leaveTime = Date.now(); // 离开页面的时间戳
  const stayDuration = (leaveTime - enterTime) / 1000; // 计算停留时长，单位为秒
  alert(stayDuration)
  console.log(stayDuration)
});

const getCampaignInfo = async () => {
  try {
    await campaignInfo(campaignUuid).then((response)=>{
      if (response.data.uuid) {
        dataInfo.value = response.data;
        if(dataInfo.value.registration.cta_info.length == 2){
          ctaType.value = dataInfo.value.registration.cta_info[0]
          ctaUuid.value = dataInfo.value.registration.cta_info[1]
        }
        console.log(dataInfo.value)
        initWechat(dataInfo.value.name,dataInfo.value.introduce.introduce,imgUrl.value)
        isLoadInfo.value = true

        updateCountdown();
        intervalId = setInterval(updateCountdown, 60000); // 每分钟更新一次
      }
    });
  } catch (e) {
    console.error(e);
  }
};


onUnmounted(() => {
  clearInterval(intervalId);
});

// 获取注册状态
const getRegisterStatus = async () => {
  try {
    const response = await checkRegister({
      omni_user_uuid: omniUserUuid,
      campaign_uuid: campaignUuid
    });
    if (response.data.status) {
      isRegister.value = response.data.status;
    }
  } catch (e) {
    console.error(e);
  }
};

// 获取演讲者信息
// const getSpeaker = (name: string) => {
//   return dataInfo.value.speaker.speakers.find((speaker) => speaker.name === name) || null;
// };
const speakersMap = computed(() => {
  const map = new Map<string, { name: string; desc: string; thumb: string }>();
  dataInfo.value.speaker.speakers.forEach(speaker => {
    map.set(speaker.name, {
      name: speaker.name,
      desc: speaker.desc,
      thumb: speaker.thumb
    });
  });
  return map;
});
// 使用计算属性获取演讲者信息
const getSpeaker = (name: string) => speakersMap.value.get(name) ?? null;


// 获取演讲者描述，如果找不到则返回默认值
const getSpeakerDescription = (name: string, key: keyof { desc: string; thumb: string; name:string}) => {
  const speaker = getSpeaker(name);
  return speaker ? speaker[key] : '';
};




// 处理联系方式点击
const dealContact = (contact: { code: string; name: string; value: string }) => {
  switch (contact.code) {
    case "website":
      window.location.href = "https://" + contact.value;
      break;
    case "mobile":
      window.location.href = `tel:${contact.value}`;
      break;
    case "email":
      copyText(contact.value);
      break;
  }
};



const register = () => {
  if (!isRegister.value) {
    ctaShow.value = true;
  } else {
    console.log("成功");
  }
};


// 格式化日期
const formattedDate = computed(() => {
  const start = moment(dataInfo.value.start_at);
  const end = moment(dataInfo.value.end_at);

  const startMonthDay = start.format('MM/DD');
  const startHourMinute = start.format('HH:mm');

  const endMonthDay = end.format('MM/DD');
  const endHourMinute = end.format('HH:mm');

  return startMonthDay === endMonthDay
      ? `${startMonthDay} ${startHourMinute} - ${endHourMinute}`
      : `${startMonthDay} ${startHourMinute} - ${endMonthDay} ${endHourMinute}`;
});


const handleCtaStatusUpdate = (val: boolean ) => {
  isRegister.value = val;
  ctaShow.value = false;
  logRecordAction("campaign_register")
};


const logRecordAction = async (action_code: string) => {
  try {
    await logRecord({
      omni_user_uuid: omniUserUuid,
      action_code,
      entity_id: campaignUuid,
      extra_data: {
        campaign_uuid: campaignUuid,
        agg_uuid: aggListUuid
      },
      push_uuid:pushId
    });
  } catch (error) {
    console.error('记录日志时出错:', error);
  }
};



</script>


<style scoped>
.van-step::after {
  display: none;
}
</style>
